# coding: utf-8
from django.http import JsonResponse
from django.http import Http404
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, get_user, login, logout
from django.contrib.auth.decorators import login_required
from apps.sales_man.models import EnterApplyInfo
from core.tools.paginator import DjangoPaginator
from apps.c2cAdmin.forms import LoginForm
from core.tools.mysql_connect import SqlModel


@login_required(login_url="/c2c/car/login")
def index(request):
    return render(request, "c2c/car_loan/index.html")


@login_required(login_url="/c2c/car/login")
def enter_list(request):
    using = request.GET.get("using")
    if not using:
        using = 'default'
    name = request.GET.get("name")
    tel = request.GET.get("tel")
    car_card = request.GET.get("car_card")
    status = request.GET.get("status")
    page = request.GET.get("page")
    info = EnterApplyInfo.objects.all().using(using)
    if name:
        info = info.filter(single__applicant__name__contains=name).using(using)
    if tel:
        info = info.filter(single__applicant__tel__contains=tel).using(using)
    if car_card:
        info = info.filter(car_card__contains=car_card).using(using)
    if status:
        info = info.filter(status=status).using(using)
    info, page_dict = DjangoPaginator.get_paging(info, page=page)
    json_list = []
    for i in info:
        d = dict()
        if using == "klb":
            sql_model = SqlModel(database='klb')
            single_id = i.single_id
            sql = "select jinrong_applicantlist.name, jinrong_applicantlist.tel from sales_man_single, jinrong_applicantlist where sales_man_single.id = %s AND  sales_man_single.apply_id = jinrong_applicantlist.id" % single_id
            sql_model.cursor.execute(sql)
            c_result = sql_model.cursor.fetchall()  # 获取查询的所有记录
            d["name"] = c_result[0][0]
            d["tel"] = c_result[0][1]
        else:
            d["name"] = i.single.applicant.name
            d["tel"] = i.single.applicant.tel
        d["age"] = i.age
        d["kilometer"] = i.kilometer
        d["city"] = i.city.name
        d["car_card"] = i.car_card
        d["status"] = i.status
        d["status_desc"] = i.get_status_display()
        d["is_close"] = i.is_close
        d["e_pk"] = i.pk
        d["cash"] = i.cash
        d["create_time"] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        if i.buy_cash:
            d["buy_cash"] = i.buy_cash
        else:
            d["buy_cash"] = "未填写"
        json_list.append(d)
    status_list = []
    for i in EnterApplyInfo.STATUS:
        d = dict()
        d['keys'] = i[0]
        d['keys_desc'] = i[1]
        status_list.append(d)
    content = {"data_list": json_list, "page_dict": page_dict, "status_list": status_list}
    return JsonResponse(content)


@login_required(login_url="/c2c/car/login")
def update_status(request):
    enter_id = request.POST.get("e_pk")
    status = request.POST.get("status")
    using = request.GET.get("using")
    if not using:
        using = 'default'
    info = EnterApplyInfo.objects.using(using).get(pk=enter_id)
    if info.is_close:
        content = {"status": "ok", "msg": "此订单已结算不能更改"}
    else:
        if status.isdigit():
            info.status = status
            info.save()
            content = {"status": "ok", "msg": "修改成功"}
        else:
            content = {"status": "error", "msg": "错误参数"}
    return JsonResponse(content)


@login_required(login_url="/c2c/car/login")
def update_cash(request):
    enter_id = request.POST.get("e_pk")
    cash = request.POST.get("cash")
    using = request.GET.get("using")
    if not using:
        using = 'default'
    info = EnterApplyInfo.objects.using(using).get(pk=enter_id)
    if info.is_close:
        content = {"status": "ok", "msg": "此订单已结算不能更改"}
    else:
        info.cash = cash
        info.save()
        content = {"status": "ok", "msg": "修改成功"}
    return JsonResponse(content)


def my_login(request):
    """
    登录页面
    @param request:
    @return:
    """
    user = get_user(request)  # 获取此用户
    next_url = request.GET.get('next', '')
    if user.is_authenticated():  # 已经登录了
        user = get_user(request)  # 获取此用户
        try:
            user_info = user.userinfo
        except Exception as e:
            logout(request)
        return redirect("/c2c/car/index")
    else:
        if request.method == "POST":
            login_form = LoginForm(request.POST)  # 获得一个form对象,传入POST的参数
            if login_form.is_valid():
                username = login_form.cleaned_data["username"]
                password = login_form.cleaned_data["password"]
                user = authenticate(username=username, password=password)  # 验证
                if user:  # 验证通过
                    user.backend = 'django.contrib.auth.backends.ModelBackend'  # 被此配置的backend验证通过
                    login(request, user)
                    if next_url:
                        return redirect(next_url)
                    else:
                        url = "/c2c/car/index"
                        return redirect(url)
                else:
                    login_form.errors["message"] = "用户名或密码错误!"
                    return render(request, "c2c/car_loan/login.html", locals())
            else:
                return render(request, "c2c/car_loan/login.html", locals())
        else:
            login_form = LoginForm()
            return render(request, "c2c/car_loan/login.html", locals())


def my_logout(request):
    logout(request)
    return redirect("/c2c/car/index")
